package com.morder.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.morder.Info;
import com.morder.R;
import com.morder.adapter.CarteAdapter;
import com.morder.databases.DbAdapter;
import com.morder.databases.DbHelper;
import com.morder.util.MOrderHelper;
import com.morder.widget.PullToRefreshListView;
import com.morder.widget.PullToRefreshListView.OnRefreshListener;

public class CarteActivity extends Activity {
  List<Info> listBlog = new ArrayList<Info>();

  int pageIndex = 1;// 页码

  private PullToRefreshListView mListView;
  private CarteAdapter adapter;// 数据源

  private ProgressBar mBodyProgressBar;
  private LinearLayout mViewFooter;// footer view

  private DbAdapter mDb;
  private int lastItem;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.carte_activity);
    mDb = DbHelper.getDb();
    InitialControls();
    BindControls();
    new PageTask(0, true).execute();
  }

  /**
   * 初始化列表
   */
  private void InitialControls() {
    mListView = (PullToRefreshListView) findViewById(R.id.list);

    mBodyProgressBar = (ProgressBar) findViewById(R.id.couponList_progressBar);
    mBodyProgressBar.setVisibility(View.VISIBLE);

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mViewFooter = (LinearLayout) inflater.inflate(R.layout.listview_footer, null, false);
  }

  /**
   * 绑定事件
   */
  private void BindControls() {
    // 上拉刷新
    ((PullToRefreshListView) mListView).setOnRefreshListener(new OnRefreshListener() {
      @Override
      public void onRefresh() {
        new PageTask(-1, true).execute();
      }
    });

    mListView.setOnScrollListener(new OnScrollListener() {
      /**
       * 下拉到最后一行
       */
      @Override
      public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (lastItem == adapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
          TextView tvFooterMore = (TextView) findViewById(R.id.tvFooterMore);
          tvFooterMore.setText(R.string.pull_to_refresh_more_label);
          tvFooterMore.setVisibility(View.VISIBLE);
          ProgressBar list_footer_progress = (ProgressBar) findViewById(R.id.list_footer_progress);
          list_footer_progress.setVisibility(View.GONE);
          LinearLayout tvMore = (LinearLayout) findViewById(R.id.tvMore);
          tvMore.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
              pageIndex = pageIndex + 1;
              new PageTask(pageIndex, false).execute();
            }
          });
        }
      }

      @Override
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        lastItem = firstVisibleItem - 2 + visibleItemCount;
      }
    });
  }

  /**
   * 多线程启动（用于上拉加载、初始化、下载加载、刷新）
   * 
   */
  public class PageTask extends AsyncTask<String, Integer, List<Info>> {
    boolean isRefresh = false;
    int curPageIndex = 0;
    boolean isLocalData = false;// 是否是从本地读取的数据

    public PageTask(int page, boolean isRefresh) {
      curPageIndex = page;
      this.isRefresh = isRefresh;
    }

    protected List<Info> doInBackground(String... params) {
      boolean isNetworkAvailable = MOrderHelper.networkIsAvailable(getApplicationContext());

      int _pageIndex = curPageIndex;
      if (_pageIndex <= 0) {
        _pageIndex = 1;
      }

      // 优先读取本地数据
      List<Info> listBlogLocal = mDb.getInfoListByPage(_pageIndex, 10);
      if (isNetworkAvailable) {// 有网络情况
        List<Info> listBlogNew = MOrderHelper.getInfoList(_pageIndex);
        switch (curPageIndex) {
        case -1:// 上拉\
          List<Info> listTmp = new ArrayList<Info>();
          if (listBlog != null && listBlog.size() > 0) {// 避免首页无数据时
            if (listBlogNew != null && listBlogNew.size() > 0) {
              int size = listBlogNew.size();
              for (int i = 0; i < size; i++) {
                System.out.println("listBlog: " + listBlog);
                System.out.println("listBlogNew.get(i): " + listBlogNew.get(i));
                System.out.println("contains: " + listBlog.contains(listBlogNew.get(i)));
                if (!listBlog.contains(listBlogNew.get(i))) {// 避免出现重复
                  listTmp.add(listBlogNew.get(i));
                }
              }
            }
          }
          return listTmp;
        case 0:// 首次加载
        case 1:// 刷新
          if (listBlogNew != null && listBlogNew.size() > 0) {
            return listBlogNew;
          }
          break;
        default:// 下拉
          List<Info> listT = new ArrayList<Info>();
          if (listBlog != null && listBlog.size() > 0) {// 避免首页无数据时
            if (listBlogNew != null && listBlogNew.size() > 0) {
              int size = listBlogNew.size();
              for (int i = 0; i < size; i++) {
                if (!listBlog.contains(listBlogNew.get(i))) {// 避免出现重复
                  listT.add(listBlogNew.get(i));
                }
              }
            }
          }
          return listT;
        }
      } else {// 无网络情况
        isLocalData = true;
        if (curPageIndex == -1) {// 上拉不加载数据
          return null;
        }
        return listBlogLocal;
      }

      return null;
    }

    @Override
    protected void onCancelled() {
      super.onCancelled();
    }

    /**
     * 加载内容
     */
    @Override
    protected void onPostExecute(List<Info> result) {
      // 网络不可用并且本地没有保存数据
      if (result == null || result.size() == 0) {// 没有新数据
        ((PullToRefreshListView) mListView).onRefreshComplete();
        if (!MOrderHelper.networkIsAvailable(getApplicationContext()) && curPageIndex > 1) {// 下拉并且没有网络
          Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_SHORT).show();
          // listView.removeFooterView(viewFooter);
          TextView tvFooterMore = (TextView) findViewById(R.id.tvFooterMore);
          tvFooterMore.setText(R.string.pull_to_refresh_more_label);
          tvFooterMore.setVisibility(View.VISIBLE);
          ProgressBar list_footer_progress = (ProgressBar) findViewById(R.id.list_footer_progress);
          list_footer_progress.setVisibility(View.GONE);
        }
        return;
      }
      int size = result.size();
      if (size >= 10 && mListView.getFooterViewsCount() == 0) {
        mListView.addFooterView(mViewFooter);
      }

      // 保存到数据库
      if (!isLocalData) {
        mDb.SynchronyData2DB(result);
      }

      if (curPageIndex == -1) {// 上拉刷新
        adapter.insertData(result);
      } else if (curPageIndex == 0) {// 首次加载
        listBlog = result;// dbHelper.GetTopBlogList();

        mBodyProgressBar.setVisibility(View.GONE);
        adapter = new CarteAdapter(listBlog, getApplicationContext());
        mListView.setAdapter(adapter);

        // 传递参数
        ((PullToRefreshListView) mListView).SetDataRow(listBlog.size());
        ((PullToRefreshListView) mListView).SetPageSize(10);
      } else if (curPageIndex == 1) {// 刷新
        try {// 避免首页无网络加载，按刷新按钮
          listBlog = result;
          if (adapter != null && adapter.getData() != null) {
            adapter.getData().clear();
            adapter.addMoreData(listBlog);
          } else if (result != null) {
            adapter = new CarteAdapter(listBlog, getApplicationContext());
            mListView.setAdapter(adapter);
          }
          // 传递参数
          ((PullToRefreshListView) mListView).SetDataRow(listBlog.size());
          ((PullToRefreshListView) mListView).SetPageSize(10);
        } catch (Exception ex) {
          // Log.e("BlogActivity", ex.getMessage());
        }
      } else {// 下拉
        adapter.addMoreData(result);
      }

      if (isRefresh) {// 刷新时处理
        ((PullToRefreshListView) mListView).onRefreshComplete();
      }
    }

    @Override
    protected void onPreExecute() {
      // 主体进度条
      if (mListView.getCount() == 0) {
        mBodyProgressBar.setVisibility(View.VISIBLE);
      }

      if (!isRefresh) {// 底部控件，刷新时不做处理
        TextView tvFooterMore = (TextView) findViewById(R.id.tvFooterMore);
        tvFooterMore.setText(R.string.pull_to_refresh_refreshing_label);
        tvFooterMore.setVisibility(View.VISIBLE);
        ProgressBar list_footer_progress = (ProgressBar) findViewById(R.id.list_footer_progress);
        list_footer_progress.setVisibility(View.VISIBLE);
      }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
    }
  }

}